﻿using KAKA.Domain;
using KAKA.Models;
using KAKA.Repository;
using Morus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcContrib;

namespace KAKA.Controllers
{
    public class MessageController : BaseController
    {
        public MessageController()
            : base()
        {
            MessageRepository = IoC.Resolve<IMessageRepository>();
        }

        public IMessageRepository MessageRepository { get; private set; }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Send(string receiver, string post)
        {
            var model = new SendMessageModel
            {
                Receiver = receiver,
                Post = post
            };

            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Send(SendMessageModel model)
        {
            var message = new Message
            {
                Content = model.Content,
                CreateAt = DateTime.Now,
                User = UserRepository.Get(CurrentUser.Id),
                Status = MessageStatus.None,
                Subject = model.Subject
            };

            if (model.Post.IsNotEmpty())
            {
                message.Post = MessageRepository.GetPost(model.Post.ToGuid());
            }

            message.Notifications.Add(new Notification
            {
                Read = false,
                Status = MessageStatus.None,
                User = UserRepository.Get(model.Receiver.ToGuid())
            });

            MessageRepository.Add(message);
            MessageRepository.Commit();

            return View();
        }

        public ActionResult Get(string post)
        {
            var message = MessageRepository.GetPost(post.ToGuid());

            if (message.Notifications.Any(r => r.User.Id == CurrentUser.Id) == false)
            {
                return this.RedirectToAction(r => r.Index());
            }

            var model = new MessageModel
            {
                Subject = message.Subject,
                Content = message.Content,
                CreateAt = message.CreateAt.ToString("yyyy-MM-dd HH:mm:ss"),
                Sender = message.User.Id.Shrink(),
            };

            return View(model);
        }

    }
}
